#include "head.h"

// typedef struct train{
//     int length;
//     char data[1000];
// }train_t;



int transFile(int netfd){
    train_t train;

    char filename[]="file1";
    train.length=5;
    memcpy(train.data,filename,train.length);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);

    struct  stat statbuf;
    bzero(&statbuf,sizeof(statbuf));
    stat(filename,&statbuf);
    off_t filesize=statbuf.st_size;
    printf("filename=%s , filesize=%ld\n",filename,filesize);
    train.length=sizeof(filesize);
    memcpy(&train.data,&filesize,train.length);
    send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netfd,train.data,train.length,MSG_NOSIGNAL);
    
    int fd=open(filename,O_RDWR);
    // while(1){
    //     bzero(&train,sizeof(train)); //添加清零操作，建议做。
    //     ssize_t sret=read(fd,train.data,sizeof(train.data));
    //     train.length=sret;
    //     send(netfd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    //     if(train.length==0){
    //         printf("服务端传输文件完成\n");
    //         break;
    //     }
    //     send(netfd,train.data,train.length,MSG_NOSIGNAL);
    // }

    char *p=(char*) mmap(NULL,train.length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    send(netfd,p,filesize,MSG_NOSIGNAL);
    munmap(p,filesize);
    

    close(fd);
    return 0;
}


//版本3.0
// int transFile(int netfd){
//     train_t train;
//     char filename[]="file1";
//     train.length=5;
//     memcpy(train.data,filename,train.length);
//     send(netfd,&train.length,sizeof(train.length),0);
//     send(netfd,train.data,train.length,0);

//     int fd=open(filename,O_RDWR);
//     while(1){
//         bzero(&train,sizeof(train)); //添加清零操作，建议做。
//         ssize_t sret=read(fd,train.data,sizeof(train.data));
//         // send(netfd,&sret,sizeof(sret),0);
//         train.length=sret;
//         send(netfd,&train.length,sizeof(train.length),0);
//         if(train.length==0){
//             printf("服务端传输文件完成\n");
//             break;
//         }
//         // send(netfd,train.data,sret,0);
//         send(netfd,train.data,train.length,0);
//     }

//     close(fd);
//     return 0;
// }

